import { selectors, groupConfig } from './config.js';

// 检查元素是否为白色圆角容器
function isWhiteCardContainer(element) {
  if (!element || element.tagName.toLowerCase() !== 'div') {
    return false;
  }
  
  const style = element.style;
  const computedStyle = window.getComputedStyle(element);
  
  // 检查背景色是否为白色或白色渐变
  const background = style.background || computedStyle.background;
  const backgroundColor = style.backgroundColor || computedStyle.backgroundColor;
  const isWhite = 
    // 纯白色背景
    groupConfig.container.backgroundColor.some(color => 
      backgroundColor === color
    ) ||
    // 白色渐变背景
    (background && groupConfig.container.backgroundGradient.some(gradient => 
      background.includes(gradient)
    ));
  
  // 检查是否有圆角
  const borderRadius = style.borderRadius || computedStyle.borderRadius;
  const hasBorderRadius = !groupConfig.container.borderRadius.not.includes(borderRadius);
  
  // 检查元素本身是否是卡片
  const isCardElement = groupConfig.card.classes.some(className => 
    element.classList.contains(className.replace('.', ''))
  );
  
  return {
    isWhite,
    hasBorderRadius,
    isCardElement
  };
}

// 检查元素是否是卡片容器（而不是分组容器）
function isCardContainer(element) {
  // 检查元素本身是否是卡片
  if (groupConfig.card.classes.some(className => 
    element.classList.contains(className.replace('.', ''))
  )) {
    return true;
  }
  
  // 检查是否只包含卡片元素
  const children = Array.from(element.children);
  if (children.length === 0) return false;
  
  // 如果所有子元素都是卡片，则认为是卡片容器
  return children.every(child => 
    groupConfig.card.classes.some(className => 
      child.classList.contains(className.replace('.', ''))
    )
  );
}

// 递归查找标题
export function findTitle(container) {
  // 获取直接子元素
  const children = Array.from(container.children);
  
  // 如果子元素少于2个，继续递归查找
  if (children.length < 2) {
    if (children.length === 1) {
      return findTitle(children[0]);
    }
    return null;
  }
  
  // 找到第一个div
  const firstDiv = children[0];
  
  // 在第一个div中递归查找第一个span
  function findFirstSpan(element) {
    // 如果当前元素是span，返回其文本内容
    if (element.tagName.toLowerCase() === 'span') {
      return element.textContent.trim();
    }
    
    // 递归查找子元素
    for (const child of element.children) {
      const result = findFirstSpan(child);
      if (result) {
        return result;
      }
    }
    
    return null;
  }
  
  return findFirstSpan(firstDiv);
}

// 检查元素是否可见
export function isElementVisible(element) {
  if (!element) return false;
  
  const style = window.getComputedStyle(element);
  return style.display !== 'none' && 
         style.visibility !== 'hidden' && 
         style.opacity !== '0' &&
         element.offsetWidth > 0 &&
         element.offsetHeight > 0;
}

// 生成分组容器标识符
function generateGroupIdentifier(container, index) {
  const title = findTitle(container) || `未命名`;
  return `group-${index}-${title}`;
}

// 设置元素标识符
function setElementIdentifier(element, identifier) {
  // 确保只写入一次
  if (!element.getAttribute('data-tracker-id')) {
    element.setAttribute('data-tracker-id', identifier);
  }
  return identifier;
}

// 获取元素标识符
function getElementIdentifier(element) {
  return element.getAttribute('data-tracker-id') || 'unknown';
}

// 查找所有分组容器
export function findAllGroupContainers(root, startElement = null) {
  const containers = [];
  const reasons = [];
  
  // 确定搜索范围
  let searchRoot = root;
  let startRect = null;
  
  if (startElement) {
    console.log('【findAllGroupContainers】指定起始元素:', getElementIdentifier(startElement));
    // 如果指定了起始元素，从该元素开始搜索
    searchRoot = startElement;
    startRect = startElement.getBoundingClientRect();
    
    // 先搜索起始元素内部
    const innerContainers = findAllGroupContainersInElement(startElement);
    console.log('【findAllGroupContainers】起始元素内部容器:', innerContainers.containers.map(c => getElementIdentifier(c)));
    containers.push(...innerContainers.containers);
    reasons.push(...innerContainers.reasons);
    
    // 然后搜索起始元素之后的元素
    const afterContainers = findAllGroupContainersAfterElement(root, startElement);
    console.log('【findAllGroupContainers】起始元素之后容器:', afterContainers.containers.map(c => getElementIdentifier(c)));
    containers.push(...afterContainers.containers);
    reasons.push(...afterContainers.reasons);
    
    return { containers, reasons };
  }
  
  // 如果没有指定起始元素，搜索整个root
  console.log('【findAllGroupContainers】搜索整个root');
  return findAllGroupContainersInElement(root);
}

// 在指定元素内部查找分组容器
function findAllGroupContainersInElement(element, startElement = null) {
  const containers = [];
  const reasons = [];
  
  // 获取从startElement到根元素的路径
  const pathToRoot = [];
  let current = startElement;
  while (current && current !== document.documentElement) {
    pathToRoot.unshift(current);
    current = current.parentElement;
  }
  
  // 如果指定了startElement，先处理startElement本身
  if (startElement) {
    const styleCheck = isWhiteCardContainer(startElement);
    const hasTitle = findTitle(startElement) !== null;
    const isCard = isCardContainer(startElement);
    const identifier = setElementIdentifier(startElement, generateGroupIdentifier(startElement, 0));
    const reason = {
      identifier,
      hasWhiteCardClass: startElement.classList.contains(selectors.groupContainer.replace('.', '')),
      isWhite: styleCheck.isWhite,
      hasBorderRadius: styleCheck.hasBorderRadius,
      isCardElement: styleCheck.isCardElement,
      isCardContainer: isCard,
      hasTitle: hasTitle
    };
    
    if (styleCheck.isWhite && 
        styleCheck.hasBorderRadius && 
        !startElement.classList.contains(selectors.groupContainer.replace('.', '')) &&
        !isCard) {
      containers.push(startElement);
      reasons.push(reason);
    }
  }
  
  // 遍历从startElement到根元素的路径
  for (const pathElement of pathToRoot) {
    // 处理当前路径元素的所有兄弟元素
    const siblings = Array.from(pathElement.parentElement.children);
    const startIndex = siblings.indexOf(pathElement);
    
    // 处理当前路径元素之后的兄弟元素
    for (let i = startIndex + 1; i < siblings.length; i++) {
      const sibling = siblings[i];
      const styleCheck = isWhiteCardContainer(sibling);
      const hasTitle = findTitle(sibling) !== null;
      const isCard = isCardContainer(sibling);
      const identifier = setElementIdentifier(sibling, generateGroupIdentifier(sibling, containers.length));
      const reason = {
        identifier,
        hasWhiteCardClass: sibling.classList.contains(selectors.groupContainer.replace('.', '')),
        isWhite: styleCheck.isWhite,
        hasBorderRadius: styleCheck.hasBorderRadius,
        isCardElement: styleCheck.isCardElement,
        isCardContainer: isCard,
        hasTitle: hasTitle
      };
      
      if (styleCheck.isWhite && 
          styleCheck.hasBorderRadius && 
          !sibling.classList.contains(selectors.groupContainer.replace('.', '')) &&
          !isCard) {
        containers.push(sibling);
        reasons.push(reason);
      }
    }
  }
  
  // 查找带有 white-card 类的容器
  const whiteCardContainers = Array.from(element.querySelectorAll(selectors.groupContainer))
    .filter(container => isElementVisible(container));
    
  whiteCardContainers.forEach((container, index) => {
    const styleCheck = isWhiteCardContainer(container);
    const hasTitle = findTitle(container) !== null;
    const isCard = isCardContainer(container);
    const identifier = setElementIdentifier(container, generateGroupIdentifier(container, containers.length + index));
    const reason = {
      identifier,
      hasWhiteCardClass: true,
      isWhite: styleCheck.isWhite,
      hasBorderRadius: styleCheck.hasBorderRadius,
      isCardElement: styleCheck.isCardElement,
      isCardContainer: isCard,
      hasTitle: hasTitle
    };
    
    // 排除卡片容器，但允许分组容器中包含卡片
    if (!isCard) {
      containers.push(container);
      reasons.push(reason);
    } else {
      console.log('排除容器:', reason);
    }
  });
  
  // 查找所有div，检查样式
  const allDivs = Array.from(element.querySelectorAll('div'))
    .filter(div => isElementVisible(div));
    
  allDivs.forEach((div, index) => {
    const styleCheck = isWhiteCardContainer(div);
    const hasTitle = findTitle(div) !== null;
    const isCard = isCardContainer(div);
    const identifier = setElementIdentifier(div, generateGroupIdentifier(div, containers.length + index));
    const reason = {
      identifier,
      hasWhiteCardClass: div.classList.contains(selectors.groupContainer.replace('.', '')),
      isWhite: styleCheck.isWhite,
      hasBorderRadius: styleCheck.hasBorderRadius,
      isCardElement: styleCheck.isCardElement,
      isCardContainer: isCard,
      hasTitle: hasTitle
    };
    
    // 排除卡片容器，但允许分组容器中包含卡片
    if (styleCheck.isWhite && 
        styleCheck.hasBorderRadius && 
        !div.classList.contains(selectors.groupContainer.replace('.', '')) &&
        !isCard) {
      containers.push(div);
      reasons.push(reason);
    } else {
      console.log('排除容器:', reason);
    }
  });
  
  return { containers, reasons };
}

// 在指定元素之后查找分组容器
function findAllGroupContainersAfterElement(root, startElement) {
  const containers = [];
  const reasons = [];
  const startRect = startElement.getBoundingClientRect();
  
  // 获取所有可能的分组容器
  const allContainers = findAllGroupContainersInElement(root);
  
  // 过滤出在起始元素之后的容器
  allContainers.containers.forEach((container, index) => {
    const rect = container.getBoundingClientRect();
    const isAfterStart = rect.top > startRect.top;
    
    if (isAfterStart) {
      containers.push(container);
      reasons.push(allContainers.reasons[index]);
    } else {
      allContainers.reasons[index].filteredOut = '在起始元素之前';
    }
  });
  
  return { containers, reasons };
}

// 导出获取元素标识符的函数
export { getElementIdentifier }; 